//
//  LoginViewController.m
//  HandheldHospital
//
//  Created by zhangchao on 16/2/26.
//  Copyright © 2016年 zhangchao. All rights reserved.
//

#import "LoginViewController.h"
#import <AVOSCloud/AVOSCloud.h>
#import "RegisterViewController.h"
#import "DataManager.h"
#import <AVOSCloudSNS.h>
#import <Masonry.h>
#import "RetrievePasswordViewController.h"
#import "ZC_AsynchronousBlock.h"
#import <RongIMKit/RongIMKit.h>


#define kWidth self.view.frame.size.width
#define kHeight self.view.frame.size.height
#define kShared [DataManager defaultManager]
#define kTFHeight (kHeight * 0.05)
#define kLHeight (kHeight * 0.04)

@interface LoginViewController ()<UITextFieldDelegate>
@property (nonatomic,strong) UITextField *userNameTF;
@property (nonatomic,strong) UITextField *userPwdTF;
@property (nonatomic,strong) UIButton *loginBtn;
@property (nonatomic,strong) UIButton *registerBtn;
@property (nonatomic,strong) UIButton *retrievePwdBtn;
@property (nonatomic,strong) UIButton *qqBtn;
@property (nonatomic,strong) UIButton *wxBtn;
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBarController.tabBar.hidden = YES;
    [self addViews];
    self.navigationItem.title = @"登录";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(didClickLeftBtn:)];
    
    //第三方登录
    [AVOSCloudSNS setupPlatform:AVOSCloudSNSSinaWeibo withAppKey:@"3921700954" andAppSecret:@"04b48b094faeb16683c32669824ebdad" andRedirectURI:@"http://wanpaiapp.com/oauth/callback/sina"];
    
    [AVOSCloudSNS setupPlatform:AVOSCloudSNSQQ withAppKey:@"1105046908" andAppSecret:@"RqrGGrsLXRjnwoUd" andRedirectURI:nil];
    
    
    [AVOSCloudSNS setupPlatform:AVOSCloudSNSWeiXin withAppKey:@"wxd930ea5d5a258f4f" andAppSecret:@"db426a9829e4b49a0dcac7b4162da6b6" andRedirectURI:nil];
}

//页面布局
- (void)addViews
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.userNameTF = [[UITextField alloc] init];
    self.userNameTF.placeholder = @"请输入用户名";
    self.userNameTF.layer.borderWidth = 0.5;
    self.userNameTF.layer.cornerRadius = 5;
    self.userNameTF.delegate = self;
    [self.view addSubview:self.userNameTF];
    [self.userNameTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kHeight * 0.15);
        make.left.equalTo(self.view).offset(kWidth * 0.05);
        make.right.equalTo(self.view).offset(-(kWidth * 0.05));
        make.height.equalTo(@(kTFHeight));
    }];
    
    self.userPwdTF = [[UITextField alloc] init];
    self.userPwdTF.placeholder = @"请输入密码";
    self.userPwdTF.layer.borderWidth = 0.5;
    self.userPwdTF.layer.cornerRadius = 5;
    self.userPwdTF.secureTextEntry = YES;
    self.userPwdTF.delegate = self;
    [self.view addSubview:self.userPwdTF];
    [self.userPwdTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kHeight * 0.2 + 10);
        make.left.equalTo(self.view).offset(kWidth * 0.05);
        make.right.equalTo(self.view).offset(-(kWidth * 0.05));
        make.height.equalTo(@(kTFHeight));
    }];
    
    self.loginBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [self.loginBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    self.loginBtn.layer.cornerRadius = 10;
    self.loginBtn.layer.borderWidth = 0.5;
    [self.loginBtn addTarget:self action:@selector(didClickLoginBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.loginBtn];
    [self.loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kHeight * 0.25 + 30);
        make.left.equalTo(self.view).offset(kWidth * 0.05);
        make.right.equalTo(self.view).offset(-(kWidth * 0.05));
        make.height.equalTo(@(kTFHeight));
    }];
    
    self.retrievePwdBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.retrievePwdBtn setTitle:@"忘记密码?" forState:UIControlStateNormal];
    [self.retrievePwdBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [self.retrievePwdBtn addTarget:self action:@selector(didClickRetrievePwdBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.retrievePwdBtn];
    [self.retrievePwdBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kHeight * 0.3 + 60);
        make.left.equalTo(self.view).offset(kWidth * 0.1);
        make.width.equalTo(@(kWidth * 0.3));
        make.height.equalTo(@(kLHeight));
    }];
    
    self.registerBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    [self.registerBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [self.registerBtn addTarget:self action:@selector(didClickRegisterBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.registerBtn];
    [self.registerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kHeight * 0.3 + 60);
        make.left.equalTo(self.view).offset(kWidth * 0.7);
        make.width.equalTo(@(kWidth * 0.2));
        make.height.equalTo(@(kLHeight));
    }];
    
    UILabel *label = [[UILabel alloc] init];
    [self.view addSubview:label];
    label.text = @"快捷登录";
    label.font = [UIFont systemFontOfSize:15];
    label.textAlignment = NSTextAlignmentCenter;
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.top.equalTo(self.view).offset(kHeight * 0.4 + 60);
        make.size.mas_equalTo(CGSizeMake(kWidth * 0.2, kLHeight));
    }];
    
    self.qqBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.qqBtn setImage:[UIImage imageNamed:@"Share_QQ"] forState:UIControlStateNormal];
    [self.view addSubview:self.qqBtn];
    [self.qqBtn addTarget:self action:@selector(qqAction) forControlEvents:UIControlEventTouchUpInside];
    [self.qqBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kHeight * 0.5 + 60);
        make.left.equalTo(self.view).offset(kWidth * 0.2);
        make.size.mas_equalTo(CGSizeMake(kWidth * 0.13, kWidth * 0.13));
    }];
    
    
    self.wxBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.wxBtn setImage:[UIImage imageNamed:@"Share_WeChat"] forState:UIControlStateNormal];
    [self.view addSubview:self.wxBtn];
    [self.wxBtn addTarget:self action:@selector(wxAction) forControlEvents:UIControlEventTouchUpInside];
    [self.wxBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kHeight * 0.5 + 60);
        make.right.equalTo(self.view).offset(-(kWidth * 0.2));
        make.size.mas_equalTo(CGSizeMake(kWidth * 0.13, kWidth * 0.13));
    }];
    
}

//左边按钮的点击事件
- (void)didClickLeftBtn:(UIBarButtonItem *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

//登录按钮点击事件
- (void)didClickLoginBtn
{
    [AVUser logInWithUsernameInBackground:self.userNameTF.text password:self.userPwdTF.text block:^(AVUser *user, NSError *error) {
        if (user != nil) {
            kShared.myUser = [AVUser currentUser];
            kShared.userType = [AVUser currentUser][@"userType"];
            [self login];
            
        } else {
            [self showAlertOneButtonWithTitle:@"提示" AndMessage:@"用户名或密码错误，或者未验证邮箱" AndAlertStyle:UIAlertControllerStyleAlert AndOneButtonTitle:@"确定" AndBlock:nil];
        }
    }];

}

//找回密码按钮点击事件
- (void)didClickRetrievePwdBtn:(UIButton *)sender
{
    RetrievePasswordViewController *retrievePwdVC = [[RetrievePasswordViewController alloc] init];
    [self.navigationController pushViewController:retrievePwdVC animated:YES];
}

//注册按钮点击事件
- (void)didClickRegisterBtn:(UIButton *)sender
{
    RegisterViewController *registerVC = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:registerVC animated:YES];
}

#pragma mark第三方登录
// qq第三方登陆
- (void)qqAction{
    
    [AVOSCloudSNS loginWithCallback:^(id object, NSError *error) {
        if (error) {
            NSLog(@"%@",error);
        } else {
            
            NSString *username = object[@"username"];//用户名
            NSString *avatar = object[@"avatar"];//头像
            NSString *sex = [object[@"raw-user"] objectForKey:@"gender"];//性别
            
            NSLog(@"QQ登陆成功,%@",object);
            NSLog(@"$$$$$$$$$$$$$$$$$%@",username);
            
            //将头上上传到自己账户的服务器
            AVFile *file =[AVFile fileWithURL:avatar];
            
            [AVUser loginWithAuthData:object platform:AVOSCloudSNSPlatformQQ block:^(AVUser *user, NSError *error) {
                 
                if (error) {
                    // 登录失败，可能为网络问题或 authData 无效
                    NSLog(@"失败:%@",error);
                    
                } else {
                    
                    // 登录成功
                    
                    //保存头像地址和性别
                    [[AVUser currentUser] setObject:avatar forKey:@"attached"];//头像地址
                    [AVUser currentUser][@"userType"] = @"普通用户";
                    [user setObject:[NSString stringWithFormat:@"%@",sex] forKey:@"gender"];
                    [user setObject:username forKey:@"username"];
                    
                    if (user[@"Picture"] == nil) {
                        [user setObject:file forKey:@"Picture"];//头像文件
                        
                    }
                    [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if (succeeded) {
                            
                            NSLog(@"用户名上传成功");
                            
                        }else{
                            
                            NSLog(@"失败:%@" , error);
                        }
                    }];
                    kShared.myUser = [AVUser currentUser];
                    kShared.userType = @"普通用户";
                    [self login];
                    
                }
                
            }];
            
        }
        
    }
     
                         toPlatform:AVOSCloudSNSQQ];
    
}

// 微信第三方登陆
- (void)wxAction{
    
    [AVOSCloudSNS loginWithCallback:^(id object, NSError *error) {
        
        if (error) {
            
            NSLog(@"%@",error);
            
        } else {
            
            NSString *username = object[@"username"];
            NSString *avatar = object[@"avatar"];
            NSString *sex = [object[@"raw-user"] objectForKey:@"sex"];
            
            NSLog(@"微信登陆成功,%@",object);
            NSLog(@"$$$$$$$$$$$$$$$$$%@",username);
            
            AVFile *file =[AVFile fileWithURL:avatar];
    
            [AVUser loginWithAuthData:object platform:AVOSCloudSNSPlatformWeiXin block:^(AVUser *user, NSError *error) {
                
                if (error) {
                    
                    // 登录失败，可能为网络问题或 authData 无效
                    NSLog(@"失败:%@",error);
                    
                } else {
                    // 登录成功
                    [[AVUser currentUser] setObject:avatar forKey:@"attached"];
                    [AVUser currentUser][@"userType"] = @"普通用户";
                    [user setObject:[NSString stringWithFormat:@"%@" , sex] forKey:@"gender"];
                    [user setObject:username forKey:@"username"];
                    
                    if (user[@"Picture"] == nil) {
                        
                        [user setObject:file forKey:@"Picture"];
                        
                    }
                    
                    [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        
                        if (succeeded) {
                            NSLog(@"用户名保存成功");
                        }else{
                            NSLog(@"失败:%@" , error);
                        }
                    }];
                    kShared.myUser = [AVUser currentUser];
                    kShared.userType = @"普通用户";
                    [self login];
                    
                }
            }];
        }
        
    }
                         toPlatform:AVOSCloudSNSWeiXin];
}


//登陆成功后调用此方法
- (void)login
{
    [self getToken];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        [kShared getCollectDoctorArray];
        [kShared getCollectHospitalArray];
    });
    [self.navigationController popViewControllerAnimated:YES];
}

//登录之后重新获取token
- (void)getToken
{
    [kShared getTokenWithBlock:^(NSString *token) {
       [[RCIM sharedRCIM] connectWithToken:token success:^(NSString *userId) {
        
       } error:^(RCConnectErrorCode status) {
           
       } tokenIncorrect:^{
           
       }];
    }];
}


#pragma mark触摸事件
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.userNameTF resignFirstResponder];
    [self.userPwdTF resignFirstResponder];
}

#pragma mark TextField的代理
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
